package getsubs.popnapisi;

import getsubs.model.Subtitle;
import java.io.*;
import java.util.zip.*;
import org.apache.commons.io.IOUtils;

public class PopnSubtitle implements Subtitle {

    private final String url;
    private final UrlOpener urlOpener;

    public PopnSubtitle(String url, UrlOpener urlOpener) {
        this.url = url;
        this.urlOpener = urlOpener;
    }

    String getUrl() {
        return url;
    }

    public void downloadTo(File directory) throws IOException {
        ZipInputStream zip = new ZipInputStream(openStream());
        ZipEntry entry;
        while(null!=(entry = zip.getNextEntry())) {
            OutputStream out = new FileOutputStream(new File(directory, entry.getName()));
            IOUtils.copy(zip, out);
            zip.closeEntry();
        }
    }

    private InputStream openStream() throws IOException {
        return urlOpener.openStream(url);
    }
}
